import {h, Component, render} from 'preact'

class Input extends Component {

    constructor(options) {
        super(options);
        this.state = {
            value: this.props.value,
            prevPropsValue: this.props.value,
        };
    }

    static getDerivedStateFromProps(props, state) {
        if (props.value !== state.prevPropsValue) {
            return {
                value: props.value,
                prevPropsValue: props.value,
            };
        }
        return null;
    }

    static flag = true;

    onInput = (e) => {
        if (Input.flag) {
            this.props.onInput(e);
        } else {
            this.setState({
                value: e.target.value,
            });
        }
    };
    onCompositionStart = () => {
        Input.flag = false;
    };
    onCompositionEnd = (e) => {
        Input.flag = true;
        this.props.onInput(e);
    };

    render(config) {
        return <input className="select-input-input" name={config.name}
                      value={this.state.value}
                      placeholder={config.placeholder}
                      lay-filter={config.layFilter}
                      lay-verify={config.layVerify}
                      lay-vertype={config.layVerType}
                      lay-reqtext={config.layReqText}
                      onInput={this.onInput}
                      onCompositionStart={this.onCompositionStart}
                      onCompositionEnd={this.onCompositionEnd}
        />
    }
}

export default Input;
